<template>
  <div>
    <el-dialog
      title="发放问卷"
      :visible.sync="isshow"
      width="530px"
      @close="concle"
    >
      <span>{{ title }}</span>
      <div>
        <p class="required">接收人</p>
        <div class="box" v-if="!issuperAdmin">
          <div class="item">
            <div class="head">
              <el-checkbox v-model="teachersCheckAll" @change="teacherFull"
              >教师（{{ teacherNum }}）
              </el-checkbox>
            </div>
            <div v-loading="teacherLoading" class="tree studentTree">
              <el-tree
                v-if="!teacherLoading"
                node-key="id"
                :data="teacthers"
                show-checkbox
                ref="teatree"
                :default-checked-keys="checkTeacthers"
                @check="conteaclecheckall"
              >
              </el-tree>
            </div>
          </div>
          <div class="item">
            <div class="head">
              <el-checkbox @change="studentFull" v-model="studentsCheckAll"
              >学生（{{ studentNum }}）
              </el-checkbox>
            </div>
            <div v-loading="studentLoading" class="tree studentTree">
              <el-tree
                v-if="!studentLoading"
                node-key="id"
                :data="studentData"
                show-checkbox
                ref="stutree"
                :default-checked-keys="checkstudents"
                @check="constuclecheckall"
              >
              </el-tree>
            </div>
          </div>
        </div>
        <div v-if="issuperAdmin" class="adminSend">
          <div class="checkItem">
            <div class="label">学校</div>
            <div class="check">
              <el-select
                multiple
                collapse-tags
                v-model="SchoolcheckArray"
                @change="changeschoolSelect"
                placeholder="请选择"
              >
                <el-checkbox v-model="checkSchoolAll" @change="selectschoolAll"
                >全选
                </el-checkbox
                >
                <el-option
                  v-for="(item, index) in schooloptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </div>
          </div>
          <div class="checkItem">
            <div class="label">角色</div>
            <div class="check">
              <el-select
                multiple
                collapse-tags
                v-model="RolecheckArray"
                @change="changeroleSelect"
                placeholder="请选择"
              >
                <el-checkbox v-model="checkRoleAll" @change="selectroleAll"
                >全选
                </el-checkbox
                >
                <el-option
                  v-for="(item, index) in rolesoptions"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="concle" round>取 消</el-button>
        <el-button type="primary" @click="confirmSend" round>发放</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listPost_teacher } from '@/api/schoolOrganization/teacher'
import { changeQuestion, getacceptUser, getStudents } from '@/api/questions'
import { listPost_role, listPost_school } from '@/api/school/list'

export default {
  name: 'MixedStateAdminSendQuestion',

  data() {
    return {
      studentData: [],
      isshow: false,
      title: '',
      defaultProps: {
        label: 'label',
        children: 'children'
      },
      count: 1,
      teacthers: [],
      students: '',
      checkTeacthers: [],
      checkstudents: [],
      teachersIsIndeterminate: false,
      teachersCheckAll: false,
      studentsCheckAll: false,
      id: undefined,
      acceptId: [],
      studentLoading: true,
      teacherLoading: true,
      teacherNum: 0,
      studentNum: 0,
      issuperAdmin: false,
      schooloptions: [],
      checkSchoolAll: false,
      SchoolcheckArray: [],
      rolesoptions: [],
      checkRoleAll: false,
      RolecheckArray: []
    }
  },
  methods: {
    // 获取学校
    getSchools() {
      listPost_school({
        pageNum: 1,
        pageSize: 9999
      }).then((response) => {
        this.schooloptions = response.rows
        this.schooloptions = this.schooloptions.map((item) => {
          return {
            label: item.schoolName,
            value: item.schoolId
          }
        })
      })
    },
    // 获取角色
    getRoles() {
      listPost_role().then((response) => {
        console.log(response, 'response')
        this.rolesoptions = response.data
        this.rolesoptions = this.rolesoptions.map((item) => {
          return {
            label: item.roleName,
            value: item.roleId
          }
        })
      })
    },
    // 学校全选
    selectschoolAll() {
      this.SchoolcheckArray = []
      if (this.checkSchoolAll) {
        this.schooloptions.map((item) => {
          this.SchoolcheckArray.push(item.value)
        })
        console.log(this.SchoolcheckArray, 'this.schooloptions')
      } else {
        this.SchoolcheckArray = []
      }
    },
    // 学校反选
    changeschoolSelect(val) {
      this.checkSchoolAll = val.length === this.schooloptions.length;
    },
    // 角色全选
    selectroleAll() {
      this.RolecheckArray = []
      if (this.checkRoleAll) {
        this.rolesoptions.map((item) => {
          this.RolecheckArray.push(item.value)
        })
      } else {
        this.RolecheckArray = []
      }
    },
    // 角色反选
    changeroleSelect(val) {
      this.checkRoleAll = val.length === this.rolesoptions.length;
    },
    // 获取教师列表 teacherId name
    getTeacher() {
      this.teacherLoading = true
      listPost_teacher({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId,
        status: 0
      }).then(async(response) => {
        //TODO 处理教师
        this.teacthers = await this.handleTeachterData(response.rows)
        this.teacherLoading = false
      })
    },
    // 获取学生列表
    getstudent() {
      this.studentLoading = true
      getStudents().then(async(res) => {
        this.studentData = await this.handleStudentData(res.data)
        this.studentLoading = false
      })
    },
    // 处理学生数据，将数据处理成树状结构
    handleStudentData(data) {
      let that = this
      // 处理学生已发放

      return data.reduce(function(acc, obj) {
        let branchObj = acc.find(function(el) {
          return el.id === obj.branchId
        })

        if (!branchObj) {
          branchObj = {
            id: obj.branchId,
            label: obj.branchName,
            children: []
          }
          acc.push(branchObj)
        }

        let majorObj = branchObj.children.find(function(el) {
          return el.id === obj.majorId
        })

        if (!majorObj) {
          majorObj = {
            id: obj.majorId,
            label: obj.majorName,
            children: []
          }
          branchObj.children.push(majorObj)
        }

        let classObj = majorObj.children.find(function(el) {
          return el.id === obj.classId
        })

        if (!classObj) {
          classObj = {
            id: obj.classId,
            label: obj.className,
            children: []
          }
          majorObj.children.push(classObj)
        }
        const disabled = that.acceptId.includes(obj.userId) || false
        const studentObj = {
          ...obj,
          id: obj.userId,
          label: obj.name,
          disabled
        }
        classObj.children.push(studentObj)

        return acc
      }, [])
    },
    // 处理教师数据，处理为树状结构
    handleTeachterData(data) {
      let that = this
      return data.reduce(function(acc, obj) {
        let branchObj = acc.find(function(el) {
          return el.id === obj.branchId
        })

        if (!branchObj) {
          branchObj = {
            id: obj.branchId,
            label: obj.branchName,
            children: []
          }
          acc.push(branchObj)
        }
        const disabled = that.acceptId.includes(obj.userId) || false
        const teacherObj = {
          ...obj,
          id: obj.userId,
          label: obj.name,
          disabled
        }
        branchObj.children.push(teacherObj)

        return acc
      }, [])
    },
    // 学生全选
    studentFull() {
      let arr = []
      if (this.studentsCheckAll) {
        this.studentData.forEach((e) => {
          e.children.forEach((o) => {
            o.children.forEach((i) => {
              i.children.forEach((n) => {
                if (!n.disabled) {
                  arr.push(n.userId)
                }
              })
            })
          })
        })
        this.checkstudents = arr
      } else {
        this.checkstudents.splice(0, this.checkstudents.length)
        if (this.checkstudents.length == 0) {
          this.$nextTick(() => {
            this.$refs.stutree.setCheckedKeys([])
          })
        }
      }
      this.studentNum = this.checkstudents.length
    },
    // 教师全选
    teacherFull() {
      if (this.teachersCheckAll) {
        let arr = []
        this.teacthers.forEach((e) => {
          e.children.forEach((o) => {
            if (!o.disabled) {
              arr.push(o.userId)
            }
          })
        })
        this.checkTeacthers = arr
      } else {
        this.checkTeacthers.splice(0, this.checkTeacthers.length)
        if (this.checkTeacthers.length == 0) {
          this.$nextTick(() => {
            this.$refs.teatree.setCheckedKeys([])
          })
        }
      }
      this.teacherNum = this.checkTeacthers.length
    },
    // 学生反选
    constuclecheckall(e, n) {
      let arr = []
      if (this.studentData != []) {
        this.studentData.forEach((e) => {
          e.children.forEach((o) => {
            o.children.forEach((i) => {
              i.children.forEach((n) => {
                if (!n.disabled) {
                  arr.push(n.userId)
                }
              })
            })
          })
        })
      }

      let arr1 = []
      n.checkedNodes.forEach((e) => {
        if (e.userId) {
          arr1.push(e.userId)
        }
      })
      this.studentNum = arr1.length
      this.studentsCheckAll = arr.length == arr1.length;
    },
    // 教师反选
    conteaclecheckall(e, n) {
      let arr = []
      if (this.teacthers != []) {
        this.teacthers.forEach((e) => {
          e.children.forEach((o) => {
            if (!o.disabled) {
              arr.push(o.userId)
            }
          })
        })
      }
      let arr1 = []
      n.checkedNodes.forEach((e) => {
        if (e.userId) {
          arr1.push(e.userId)
        }
      })
      this.teacherNum = arr1.length
      this.teachersCheckAll = arr.length == arr1.length;
    },
    show(row) {
      this.isshow = true
      this.title = row.surveyName
      this.id = row.id
      this.acceptUser()
      let role = this.$store.getters.roleId
      console.log(
        role,
        'this.$store.getters.roleId == "schoolAdmin"this.$store.getters.roleId == "schoolAdmin"'
      )
      if (role == 'admin') {
        this.issuperAdmin = true
      }
    },
    confirmSend() {
      if (!this.issuperAdmin) {
        this.checkstudents = this.$refs.stutree.getCheckedKeys(true)
        this.checkTeacthers = this.$refs.teatree.getCheckedKeys(true)
      }
      // 调取发送接口发送数据
      if (this.sendmsg()) {
        this.isshow = false
      }
    },
    // 非超管发放
    notSuperSend(statu) {

      if (statu) {
        const loading = this.$loading({
          lock: true,
          text: '正在发放…',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.3)'
        })
        let userId = this.checkstudents.concat(this.checkTeacthers)
        changeQuestion({
          surveyId: this.id,
          userIds: userId,
          surveyStatus: 1
          // userIds: 906,
        }).then(() => {
          loading.close()
          this.$emit('sendQuestionSucess')
        }).finally(() => {
          loading.close()
        })
      } else {
        this.$modal.msgError('请选择发放用户')
      }
    },
    // 超管发放
    SuperSend(statu) {
      if (statu) {
        const loading = this.$loading({
          lock: true,
          text: '正在发放…',
          spinner: 'el-icon-loading',
          background: 'rgba(255, 255, 255, 0.3)'
        })
        // let userId = this.checkstudents.concat(this.checkTeacthers);
        changeQuestion({
          surveyId: this.id,
          schoolIds: this.SchoolcheckArray,
          roleIds: this.RolecheckArray,
          // userIds: 906,
          surveyStatus: 1
        }).then(() => {
          loading.close()
          this.$emit('sendQuestionSucess')
        }).finally(() => {
          loading.close()
        })
      } else {
        this.$modal.msgError('请选择发放用户')
      }
    },
    // 发放
    sendmsg() {
      let statu = this.sendisno()
      if (!this.issuperAdmin) {
        this.notSuperSend(statu)
      } else {
        this.SuperSend(statu)
      }
      return statu
    },
    // 校验是否有选择发放用户
    sendisno() {
      let statu = true
      if (
        !this.issuperAdmin &&
        this.checkstudents.concat(this.checkTeacthers).length == 0
      ) {
        statu = false
      }
      if (
        this.issuperAdmin &&
        this.SchoolcheckArray.concat(this.RolecheckArray).length == 0
      ) {
        console.log('qqqqqq')
        statu = false
      }
      return statu
    },
    // 获取收到问卷用户
    async acceptUser() {
      let res = await getacceptUser({ surveyId: this.id })
      this.getTeacher()
      this.getstudent()
      if (this.issuperAdmin) {
        this.getSchools()
        this.getRoles()
      }

      this.acceptId = res.data || []
    },
    concle() {
      this.checkTeacthers = []
      this.checkstudents = []
      this.teachersCheckAll = false
      this.studentsCheckAll = false
      this.RolecheckArray = []
      this.SchoolcheckArray = []
      this.checkSchoolAll = false
      this.checkRoleAll = false;
      (this.teacherNum = 0), (this.studentNum = 0), (this.isshow = false)
    }
  }
}
</script>

<style lang="scss" scoped>
.el-checkbox {
  text-align: left;
  width: 100%;
  padding-left: 20px;
  margin-top: 5px;
  margin-bottom: 5px;
  box-sizing: border-box;
}

::v-deep .el-input--medium .el-input__inner {
  width: 250px !important;
}

.required::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}

.required {
  margin-top: 20px;
}

.box {
  display: flex;
}

.item {
  margin-right: 40px;
}

.tree {
  width: 200px;
  box-shadow: 0 0 10px 2px #ddd;
  display: flex;
  flex-direction: column;
  padding: 10px;
  margin-top: 10px;
}

.check {
  margin-left: 40px;
}

.studentTree {
  height: 400px;
  overflow: auto;
}

.head {
  padding-left: 10px;
  margin-top: 10px;
}

.checkItem {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}

.adminSend {
  margin-top: 20px;
}
</style>
